package pl.edu.mimuw.irs.rcp.controller.action;

import java.util.List;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.RootEditPart;
import org.eclipse.jface.resource.ImageDescriptor;

import pl.edu.mimuw.irs.core.model.design.IRSNodeInterface;
import pl.edu.mimuw.irs.core.model.petrinet.Place;
import pl.edu.mimuw.irs.core.model.petrinet.Transition;
import pl.edu.mimuw.irs.rcp.controller.part.IRSNodeEditPart;

/**
 * @author Jakub Rauch
 * Created on: 2009-05-21
 */
public class ExpandCollapseAction extends SelectionAction {

	// *** Static methods
	
	private static String getExpandCollapseImage(IRSNodeInterface node, Type type) {
		String imageSource = null;
		switch (type) {
			case EXPAND:
				if (node instanceof Place) imageSource = "icon/place_expand.png";
				else if (node instanceof Transition) imageSource = "icon/tran_expand.png";
				// TODO else error
				break;
			case COLLAPSE:
				if (node instanceof Place) imageSource = "icon/place_collapse.png";
				else if (node instanceof Transition) imageSource = "icon/tran_collapse.png";
				// TODO else error
				break;
			default:
				break;
		}
		return imageSource;
	}
	
	// *** Attributes
	private Type type;
	public Type getType() {
		return type;
	}
	public void setType(Type type) {
		this.type = type;
	}
	
	// *** Constructors

	public ExpandCollapseAction(IRSNodeEditPart nodeEditPart, Type type) {
		super(nodeEditPart, type.toString(), 
				ImageDescriptor.createFromFile(ExpandCollapseAction.class, 
						getExpandCollapseImage(nodeEditPart.getIRSNode(), type)));
		setType(type);
	}
	
	// *** Methods
	
	@Override
	public void run() {
		if (Type.EXPAND.equals(getType())) getNodeEditPart().getIRSNode().setExpanded(true);
		else if (Type.COLLAPSE.equals(getType())) getNodeEditPart().getIRSNode().getParent().setExpanded(false);
		
		refresh(getNodeEditPart().getParent());
		
		refresh(getNodeEditPart().getRoot());
	}
	

	@SuppressWarnings("unchecked")
	private void refresh(EditPart editPart) {
		editPart.refresh();
		List<EditPart> children = editPart.getChildren();
		if (editPart instanceof RootEditPart) {
			for (EditPart childEditPart : children) {
				refresh(childEditPart);
			}
		} else if (editPart instanceof IRSNodeEditPart) {
			IRSNodeEditPart nodeEditPart = (IRSNodeEditPart)editPart;
			IRSNodeInterface node = nodeEditPart.getIRSNode();
			if (node.isExpanded()) {
				for (EditPart childEditPart : children) {
					refresh(childEditPart);
				}
			}
		} else {
			for (EditPart childEditPart : children) {
				childEditPart.refresh();
			}
		}
	}
	
	public enum Type {
		EXPAND,
		COLLAPSE
	}
}
